import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'

// 路由配置
const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/index.vue'),
    meta: { title: '登录', requiresAuth: false }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/login/register.vue'),
    meta: { title: '注册', requiresAuth: false }
  },
  {
    path: '/',
    component: () => import('@/views/layout.vue'),
    redirect: '/dashboard',
    meta: { requiresAuth: true },
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/dashboard.vue'),
        meta: { title: '首页', icon: 'House', requiresAuth: true }
      },
      {
        path: 'user',
        name: 'User',
        component: () => import('@/views/user.vue'),
        meta: { title: '用户管理', icon: 'User', requiresAuth: true }
      },
      {
        path: 'employee',
        name: 'Employee',
        component: () => import('@/views/employee.vue'),
        meta: { title: '员工管理', icon: 'UserFilled', requiresAuth: true }
      },
      {
        path: 'medicine',
        name: 'Medicine',
        component: () => import('@/views/medicine.vue'),
        meta: { title: '药品信息管理', icon: 'FirstAidKit', requiresAuth: true }
      },
      {
        path: 'category',
        name: 'Category',
        component: () => import('@/views/category.vue'),
        meta: { title: '药品分类管理', icon: 'Collection', requiresAuth: true }
      },
      {
        path: 'stock',
        name: 'Stock',
        component: () => import('@/views/stock.vue'),
        meta: { title: '药品库存管理', icon: 'Box', requiresAuth: true }
      },
      {
        path: 'order',
        name: 'Order',
        component: () => import('@/views/order.vue'),
        meta: { title: '订单管理', icon: 'List', requiresAuth: true }
      },
      {
        path: 'address',
        name: 'Address',
        component: () => import('@/views/address.vue'),
        meta: { title: '地址管理', icon: 'Location', requiresAuth: true }
      }
    ]
  },
  {
    path: '/404',
    name: 'NotFound',
    component: () => import('@/views/404.vue'),
    meta: { title: '404', requiresAuth: false }
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/404'
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 连锁药房管理系统` : '连锁药房管理系统'
  
  // 判断是否需要登录权限
  if (to.meta.requiresAuth) {
    const userStore = useUserStore()
    if (!userStore.userId) {
      // 未登录，跳转到登录页
      next({ path: '/login', query: { redirect: to.fullPath } })
    } else {
      next()
    }
  } else {
    next()
  }
})

export default router
